package com.shengwei.truck.driver.view.ui.mine.msgCenter;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.lifecycle.Observer;

import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.databinding.MsgDetailBinding;
import com.shengwei.truck.driver.utils.DateTimeUtils;
import com.shengwei.truck.driver.utils.MyLogCat;
import com.shengwei.truck.driver.view.ui.BaseActivity;
import com.shengwei.truck.driver.view.ui.task.TaskDetailActivity;
import com.shengwei.truck.driver.vm.TaskViewModel;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;
/**
 * 消息详情
 */
public class MsgDetailActivity extends BaseActivity<TaskViewModel, MsgDetailBinding> implements View.OnClickListener {
    private String mMsgTime;
    private String mMsgTitle;
    private String mMsgContent;
    private String mTaskId;
    private String mTaskNo;
    private int mForwardShare = 0; //1转派；2共享
    private int mCurOperate = -1; //1同意；0拒绝
    String mFromPage;
    private static final String KEY_MSGID = "msg_id";//消息ID
    private static final String KEY_WHICH_PUSH_SDK = "rom_type"; //该通知的下发通道
    private static final String KEY_TITLE = "n_title";//通知标题
    private static final String KEY_CONTENT = "n_content";//通知内容
    private static final String KEY_EXTRAS = "n_extras";//通知附加字段
    private String mMark;
    private final String TAG = "MsgDetailActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        getLastIntent();
        handleOpenClick();
        this.setTitle(mMsgTitle);
        super.onCreate(savedInstanceState);
        mDataBinding.btTaskDetail.setOnClickListener(this);
        updateUI();
        initLiveDataObersve();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 创建liveData观察者，用于监听数据变化，从而更新UI
     */
    private void initLiveDataObersve() {
        mViewModel.getShareForwardVerify().observe(this, new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String> searchUserDataResult) {
                searchUserDataResult.handler(new OnCallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        String tip = null;
                        if (mForwardShare == 1) { //转派
                            if (mCurOperate == 1) {
                                tip = MsgDetailActivity.this.getResources().getString(R.string.forward_agree_ok);
                            } else {
                                tip = MsgDetailActivity.this.getResources().getString(R.string.forward_task_refuse);
                            }
                        } else if (mForwardShare == 2) { //分享
                            if (mCurOperate == 1) {
                                tip = MsgDetailActivity.this.getResources().getString(R.string.share_agree_ok);
                            } else {
                                tip = MsgDetailActivity.this.getResources().getString(R.string.forward_task_refuse);
                            }
                        }
                        Toast.makeText(MsgDetailActivity.this, tip, Toast.LENGTH_SHORT).show();
                        MsgDetailActivity.this.finish();
                    }
                });
            }
        });
    }

    @Override
    public int getContentViewId() {
        return R.layout.msg_detail;
    }

    public void getLastIntent() {
        Intent i = this.getIntent();
        Bundle bundle = i.getExtras();
        if (bundle != null) {
            mFromPage = bundle.getString("fromPage");
            try{
                if ("msgList".equals(mFromPage)) {
                    //从列表点击获取数据
                    getDataFromListItem(bundle);
                } else if ("jpushChannel".equals(mFromPage)) {
                    getDataFromJpushChannel(bundle);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return;
    }

    /**
     * 获取从列表传来的数据
     *
     * @param b
     */
    public void getDataFromListItem(Bundle b) throws JSONException {
        mMsgTitle = b.getString("title");
        mMsgTime = b.getString("time");
        mMsgContent = b.getString("content");
        if (!TextUtils.isEmpty(mMsgTitle)) {
            if (mMsgTitle.equals("转派")) {
                mForwardShare = 1;
            } else if (mMsgTitle.equals("共享")) {
                mForwardShare = 2;
            }
        }
        String paramsJsonStr = b.getString("params");
        JSONObject paramsJson = new JSONObject(paramsJsonStr);
        mTaskId = paramsJson.getString("id");
        mMark = paramsJson.getString("mark");
        mTaskNo = paramsJson.getString("taskNo");
    }


    /**
     * 点击JPUSH通道下发的通知，获取推送的通知数据
     * @param b
     */
    public void getDataFromJpushChannel(Bundle b) throws JSONException {
        mMsgTitle = b.getString("title");
        mMsgContent = b.getString("content");
        String extras = b.getString("extras");
        if (!TextUtils.isEmpty(mMsgTitle)) {
            if (mMsgTitle.equals("转派")) {
                mForwardShare = 1;
            } else if (mMsgTitle.equals("共享")) {
                mForwardShare = 2;
            }
        }
        getPushExtras(extras);
    }


    /**
     * 更新消息详情UI
     */
    private void updateUI() {
        //消息类型--对应的标题
        if (!TextUtils.isEmpty(mMsgTitle)) {
            mDataBinding.tvMsgTitle.setText(mMsgTitle);
        }
        //消息时间
        if (!TextUtils.isEmpty(mMsgTime)) {
            mDataBinding.tvMsgTime.setText(mMsgTime);
        }
        //内容
        if (!TextUtils.isEmpty(mMsgContent)) {
            mDataBinding.tvMsgContent.setText(mMsgContent);
        }

        //说明是任务消息,显示任务号。 任务消息包括（任务超时等、转派与共享也可以看作任务消息）
        if (!TextUtils.isEmpty(mTaskId)) {
            mDataBinding.btTaskDetail.setVisibility(View.VISIBLE);

            //显示任务号
            if (!TextUtils.isEmpty(mTaskNo)) {
                mDataBinding.tvTaskNoLabel.setVisibility(View.VISIBLE);
                mDataBinding.tvTaskNoValue.setVisibility(View.VISIBLE);
                mDataBinding.tvTaskNoValue.setText(mTaskNo);
            }

            //显示同意和拒绝按钮
            if ((mMsgTitle.equals("转派") || mMsgTitle.equals("共享")) ) {
                if (!TextUtils.isEmpty(mMsgContent) && (mMsgContent.contains("操作"))){
                    mDataBinding.agreeLayout.setVisibility(View.VISIBLE);
                    mDataBinding.btAgree.setOnClickListener(this);
                    mDataBinding.btRefuse.setOnClickListener(this);
                }
            }
        }

    }


    /**
     * 处理点击事件，当前启动配置的Activity都是使用
     * Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK
     * 方式启动，只需要在onCreat中调用此方法进行处理
     */
    private void handleOpenClick() {
        Log.d(TAG, "用户点击打开了通知");
        String data = null;
        //获取华为平台附带的jpush信息
        if (getIntent().getData() != null) {
            data = getIntent().getData().toString();
        }

        //获取fcm、oppo、vivo、华硕、小米平台附带的jpush信息
        if (TextUtils.isEmpty(data) && getIntent().getExtras() != null) {
            data = getIntent().getExtras().getString("JMessageExtra");
        }

        Log.w(TAG, "msg content is " + String.valueOf(data));
        if (TextUtils.isEmpty(data)) return;
        try {
            JSONObject jsonObject = new JSONObject(data);
            String msgId = jsonObject.optString(KEY_MSGID);
            byte whichPushSDK = (byte) jsonObject.optInt(KEY_WHICH_PUSH_SDK);
            String title = jsonObject.optString(KEY_TITLE);
            String content = jsonObject.optString(KEY_CONTENT);
            String extras = jsonObject.optString(KEY_EXTRAS);
            StringBuilder sb = new StringBuilder();
            sb.append("msgId:");
            sb.append(String.valueOf(msgId));
            sb.append("\n");
            sb.append("title:");
            sb.append(String.valueOf(title));
            sb.append("\n");
            sb.append("content:");
            sb.append(String.valueOf(content));
            sb.append("\n");
            sb.append("extras:");
            sb.append(String.valueOf(extras));
            sb.append("\n");
            sb.append("platform:");
            sb.append(getPushSDKName(whichPushSDK));
            MyLogCat.i(TAG, sb.toString());

            //准备页面要显示的数据
            mMsgTitle = title;  //标题
            mMsgContent = content;//内容
            //判断是转派还是分享
            if (!TextUtils.isEmpty(mMsgTitle)) {
                if (mMsgTitle.equals("转派")) {
                    mForwardShare = 1;
                } else if (mMsgTitle.equals("共享")) {
                    mForwardShare = 2;
                }
            }
            //获取推送extras中的数据
            getPushExtras(extras);
            //上报点击事件
            JPushInterface.reportNotificationOpened(this, msgId, whichPushSDK);
        } catch (JSONException e) {
            Log.w(TAG, "parse notification error");
        }
    }


    /**
     * 获取到推送下来的Extra数据
     */
    public void getPushExtras(String pushExtras) throws JSONException {
        JSONObject jsonExtra = new JSONObject(pushExtras);
        long publishTime = jsonExtra.getLong("pushTime");
        mMsgTime = DateTimeUtils.timeStampToDateString(publishTime);
        mTaskId = jsonExtra.getString("id");
        mMark = jsonExtra.getString("mark");
        mTaskNo = jsonExtra.getString("taskNo");
    }

    private String getPushSDKName(byte whichPushSDK) {
        String name;
        switch (whichPushSDK) {
            case 0:
                name = "jpush";
                break;
            case 1:
                name = "xiaomi";
                break;
            case 2:
                name = "huawei";
                break;
            case 3:
                name = "meizu";
                break;
            case 4:
                name = "oppo";
                break;
            case 5:
                name = "vivo";
                break;
            case 6:
                name = "asus";
                break;
            case 8:
                name = "fcm";
                break;
            default:
                name = "jpush";
        }
        return name;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btTaskDetail) {  //任务详情
            Intent i = new Intent(MsgDetailActivity.this, TaskDetailActivity.class);
            i.putExtra("id", mTaskId);
            startActivity(i);
        } else if (v.getId() == R.id.btAgree) {//同意转派或分享
            if (mTaskId != null) {
                mCurOperate = 1;
                mViewModel.shareForwardVerify(mTaskId, 1, mForwardShare,mMark);
            }
        } else if (v.getId() == R.id.btRefuse) {//拒绝转派或分享
            if (mTaskId != null) {
                mCurOperate = 0;
                mViewModel.shareForwardVerify(mTaskId, 0, mForwardShare,mMark);
            }
        }
    }
}
